package message.visitor.singleton;

import message.types.message.RejectedRequest;
import message.types.stalkerstring.GetUserFromNameAnswer;
import message.types.string.GetUserFromNameRequest;
import message.visitor.MessageVisitor;
import stalker.Stalker;
import stalker.user.User;

public class UserManagerVisitor extends MessageVisitor<Void> {

  public UserManagerVisitor() {
  }
  
  @Override
  public Void visit(GetUserFromNameRequest getStalkerFromName) {
    if (User.isTaken(getStalkerFromName.getName())) {
      Stalker.USER_MANAGER.acceptMessage(
          new GetUserFromNameAnswer(Stalker.USER_MANAGER,
                                    getStalkerFromName.getClient(),
                                    User.getUserFromName(getStalkerFromName.getName()),
                                    getStalkerFromName.getName())
          );
    } else {
      //no match
      Stalker.USER_MANAGER.acceptMessage(getRejectedMessage(getStalkerFromName));
    }
    return null;
  }

  @Override
  public Void visit(GetUserFromNameAnswer getStalkerFromName) {
    assert getStalkerFromName != null;
    relayMessage(getStalkerFromName);
    return null;
  }

  @Override
  public Void visit(RejectedRequest rejectedRequest) {
    
    assert rejectedRequest != null;
    
    if (rejectedRequest.getDestination().equals(Stalker.USER_MANAGER)) {
      // message arrived
      assert false;
    } else {
      relayMessage(rejectedRequest);
    }
    
    return null;
  }
  
}
